using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using ExitGames.Client.Photon;
using Rilisoft.MiniJson;
using UnityEngine;

public class TDMController : MonoBehaviour, IPunObservable
{
	[Serializable]
	public struct LocalTeam
	{
		public int idPlayer;

		public PunTeams.Team team;
	}

	public static TDMController instance;

	public static Color zombieColor = new Color(0.5019608f, 69f / 85f, 0.5294118f, 1f);

	public static PunTeams.Team _myTeam = PunTeams.Team.none;

	public int cGraid;

	private IEnumerator updateZombie;

	private float currentTimer;

	private float waitPlayersTime = 3f;

	private bool zombieEnded;

	public int zombieStart;

	private bool forceZombie;

	public bool pvpStarted;

	private PunTeams.Team _oldTeam;

	private Coroutine WaitForTeamCoroutine;

	private int nGradeWeapon;

	private List<GameObject> listUpBonuse = new List<GameObject>();

	[SerializeField]
	private List<LocalTeam> _localTeam = new List<LocalTeam>();

	public int incrementTeams;

	private IEnumerator _corotuneSortTeam;

	private int _countRedTeam;

	private int _countBlueTeam;

	public static bool isTeamGameType
	{
		get
		{
			return GameController.instance != null && (GameController.instance.curTypeGame == TypeGame.TDM || GameController.instance.curTypeGame == TypeGame.tanks || GameController.instance.curTypeGame == TypeGame.Zombe || GameController.instance.curTypeGame == TypeGame.SkyBlock || GameController.instance.curTypeGame == TypeGame.CopsAndRobbers || GameController.instance.curTypeGame == TypeGame.RocketLeague || GameController.instance.curTypeGame == TypeGame.Pixelmon || GameController.instance.curTypeGame == TypeGame.WalkingRobots);
		}
	}

	public static PunTeams.Team myTeam
	{
		get
		{
			return _myTeam;
		}
		set
		{
			BCWDebug.LogError("My team" + value);
			_myTeam = value;
		}
	}

	public static PunTeams.Team enemyTeam
	{
		get
		{
			return (myTeam == PunTeams.Team.blue) ? PunTeams.Team.red : PunTeams.Team.blue;
		}
	}

	public List<LocalTeam> localTeam
	{
		get
		{
			return _localTeam;
		}
	}

	public static event Action ChangeTeam;

	private void Awake()
	{
		instance = this;
		if (isTeamGameType)
		{
			if (_corotuneSortTeam == null)
			{
				_corotuneSortTeam = CorotuneSortTeam();
				StartCoroutine(_corotuneSortTeam);
			}
			if (PhotonNetwork.room != null && !PhotonNetwork.room.customProperties.ContainsKey(PunTeams.Team.red.ToString()))
			{
				PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
				{
					PunTeams.Team.blue.ToString(),
					0
				} });
				PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
				{
					PunTeams.Team.red.ToString(),
					0
				} });
			}
		}
		string empty = string.Empty;
		switch (GameController.instance.curTypeGame)
		{
		case TypeGame.Zombe:
		{
			ZombeSettings zombeSettings = (ZombeSettings)settings.GetSettings(TypeGame.Zombe);
			empty = JSONManager.Instance.GetJSON(URLs.ModSettings);
			if (!(empty != string.Empty))
			{
				break;
			}
			Dictionary<string, object> dictionary2 = Json.Deserialize(empty) as Dictionary<string, object>;
			if (dictionary2 == null)
			{
				break;
			}
			dictionary2 = dictionary2["ModSettings"] as Dictionary<string, object>;
			dictionary2 = dictionary2["ZombieSettings"] as Dictionary<string, object>;
			zombeSettings.zombieBoilerMultiplers = new List<BoilerSerttings>();
			List<object> list = dictionary2["Boilers"] as List<object>;
			foreach (object item in list)
			{
				Dictionary<string, object> dictionary3 = item as Dictionary<string, object>;
				zombeSettings.zombieBoilerMultiplers.Add(new BoilerSerttings(Convert.ToInt32(dictionary3["damage"]), Convert.ToInt32(dictionary3["health"])));
			}
			zombeSettings.startHumanHealth = int.Parse(dictionary2["HumanStartHealth"].ToString());
			zombeSettings.startZombieHealth = zombeSettings.zombieBoilerMultiplers[controllerConnectPhoton.thisScript.playerBoiler].health;
			zombeSettings.zombieDamage = zombeSettings.zombieBoilerMultiplers[controllerConnectPhoton.thisScript.playerBoiler].damage;
			zombeSettings.humanMoveMult = (float)int.Parse(dictionary2["HumanMove"].ToString()) / 100f;
			zombeSettings.zombieMoveMult = (float)int.Parse(dictionary2["ZombieMove"].ToString()) / 100f;
			break;
		}
		case TypeGame.Pixelmon:
		{
			empty = JSONManager.Instance.GetJSON(URLs.ModSettings);
			if (!(empty != string.Empty))
			{
				break;
			}
			Dictionary<string, object> dictionary = Json.Deserialize(empty) as Dictionary<string, object>;
			if (dictionary != null)
			{
				dictionary = dictionary["ModSettings"] as Dictionary<string, object>;
				dictionary = dictionary["PixelmonSettings"] as Dictionary<string, object>;
				if (dictionary != null)
				{
					PixelmonController.timeRound = float.Parse(dictionary["TimeRound"].ToString());
					PixelmonController.maxPixelmonsForWin = int.Parse(dictionary["MaxCaughtPixelmon"].ToString());
					PixelmonController.timeSpawnPixelmon = float.Parse(dictionary["DelaySpawnPixelmon"].ToString());
				}
			}
			break;
		}
		}
	}

	private void Start()
	{
		if (GameInfoWindow.instance != null)
		{
			GameInfoWindow.instance.ShowTDMInfo(isTeamGameType);
		}
		if (GameController.instance.curTypeGame == TypeGame.Zombe)
		{
			SetStartPVP(false);
			if (updateZombie != null)
			{
				StopCoroutine(updateZombie);
			}
			updateZombie = UpdateZombieMod();
			StartCoroutine(updateZombie);
		}
	}

	private IEnumerator UpdateZombieMod()
	{
		while (GameController.instance.curTypeGame == TypeGame.Zombe)
		{
			yield return null;
			while (PlayerBehavior.MyPlayer == null || PhotonNetwork.room == null)
			{
				yield return null;
			}
			if (!PVPManager.instance.gameIsStarted && myTeam == PunTeams.Team.blue && PhotonNetwork.isMasterClient && zombieStart == 0)
			{
				ChangeTeamFromMaster(PlayerBehavior.MyPlayer.photonView.ownerId, PunTeams.Team.red);
			}
			GameInfoWindow.instance.UpdateTitle();
			if (GameController.instance.listPlayers.Count >= settings.GetSettings(TypeGame.Zombe).minPlayerToStart && PhotonNetwork.room != null && zombieStart == 0)
			{
				if (PhotonNetwork.room.customProperties[controllerConnectPhoton._StartRaceTime] == null)
				{
					if (PhotonNetwork.isMasterClient)
					{
						PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
						{
							controllerConnectPhoton._StartRaceTime,
							(float)PhotonNetwork.time + waitPlayersTime
						} });
					}
				}
				else
				{
					if (currentTimer != (float)PhotonNetwork.room.customProperties[controllerConnectPhoton._StartRaceTime])
					{
						currentTimer = (float)PhotonNetwork.room.customProperties[controllerConnectPhoton._StartRaceTime];
						StartGameWindow.instance.StopTimer();
						GameInfoWindow.instance.lobbyButton.SetActive(false);
						if ((double)currentTimer - PhotonNetwork.time <= (double)(waitPlayersTime * 2f) && (double)currentTimer - PhotonNetwork.time > 0.0)
						{
							StartGameWindow.instance.StartTimer((float)((double)currentTimer - PhotonNetwork.time), true);
						}
					}
					if ((double)(float)PhotonNetwork.room.customProperties[controllerConnectPhoton._StartRaceTime] > PhotonNetwork.time + (double)waitPlayersTime && !PVPManager.instance.gameIsStarted)
					{
						PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
						{
							controllerConnectPhoton._StartRaceTime,
							(float)PhotonNetwork.time + waitPlayersTime
						} });
					}
					if ((double)currentTimer - PhotonNetwork.time <= 0.0)
					{
						if (!GameController.instance.playerScript.startPVP && myTeam != 0)
						{
							GameInfoWindow.instance.Hide();
							StartGameWindow.instance.StopTimer();
							GameInfoWindow.instance.lobbyButton.SetActive(true);
							zombieStart = 1;
						}
					}
					else
					{
						GameInfoWindow.instance.hidebutton.SetActive(false);
					}
				}
			}
			else if (!PVPManager.instance.gameIsStarted)
			{
				StartGameWindow.instance.StopTimer();
			}
			if (PlayerBehavior.MyPlayer.localTeam != 0 && PVPManager.instance != null && PVPManager.instance.gameIsStarted)
			{
				int countRed = 0;
				int countBlue = 0;
				for (int j = 0; j < GameController.instance.listPlayers.Count; j++)
				{
					if (GameController.instance.listPlayers[j].localTeam == PunTeams.Team.red)
					{
						countRed++;
					}
					else if (GameController.instance.listPlayers[j].localTeam == PunTeams.Team.blue)
					{
						countBlue++;
					}
				}
				int countLocalRed = 0;
				int countLocalBlue = 0;
				for (int i = 0; i < _localTeam.Count; i++)
				{
					if (_localTeam[i].team == PunTeams.Team.red)
					{
						countLocalRed++;
					}
					else if (_localTeam[i].team == PunTeams.Team.blue)
					{
						countLocalBlue++;
					}
				}
				if (!controllerConnectGame.afterRecconect && (countBlue == 0 || countLocalBlue == 0) && PlayerBehavior.MyPlayer.props.startPVP)
				{
					BCWDebug.LogError("********************** blue team", "zombie");
					PVPManager.instance.TimeOut();
				}
				else if (!controllerConnectGame.afterRecconect && (countRed == 0 || countLocalRed == 0) && PlayerBehavior.MyPlayer.props.startPVP)
				{
					BCWDebug.LogError("*********************** red team", "zombie");
					PVPManager.instance.TimeOut();
				}
			}
			else if (!controllerConnectGame.afterRecconect && PVPManager.instance.GetTime() >= (double)PVPManager.timeRound && PlayerBehavior.MyPlayer.props.startPVP && !forceZombie)
			{
				forceZombie = true;
				PVPManager.instance.TimeOut();
			}
		}
	}

	public void EndZombie()
	{
		_oldTeam = PunTeams.Team.none;
		SetStartPVP(false);
		GameInfoWindow.instance.title.gameObject.SetActive(false);
		cGraid = 0;
		PlayerBehavior.MyPlayer.CancelRespawn();
		GameInfoWindow.instance.lobbyButton.SetActive(true);
		if (updateZombie != null)
		{
			StopCoroutine(updateZombie);
		}
		updateZombie = UpdateZombieMod();
		StartCoroutine(updateZombie);
		DestroyUpBonuse();
	}

	public void RestartTDM()
	{
		if (BCWFlagManager.instance != null)
		{
			BCWFlagManager.instance.winerTeam = PunTeams.Team.none;
			BCWFlagManager.instance.ClearPlayers();
		}
		if (BCWFlagController.instance != null)
		{
			BCWFlagController.instance.winnerTeam = TDMResult.None;
		}
		if (PhotonNetwork.room != null)
		{
			PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
			{
				PunTeams.Team.blue.ToString(),
				0
			} });
			PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
			{
				PunTeams.Team.red.ToString(),
				0
			} });
		}
		PlayerBehavior.MyPlayer.Points = 0;
		PhotonPlayer[] playerList = PhotonNetwork.playerList;
		foreach (PhotonPlayer player in playerList)
		{
			player.SetScore(0);
		}
	}

	public void SetStartPVP(bool val)
	{
		PhotonNetwork.player.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
		{
			PlayerPropsKeys.startPVP,
			val
		} });
		pvpStarted = val;
		if (GameController.instance.playerScript != null)
		{
			GameController.instance.playerScript.startPVP = val;
		}
		if (val && PVPManager.kickInactive != null)
		{
			StopCoroutine(PVPManager.kickInactive);
		}
		if (val)
		{
			SendStatisticsOnStartRound();
		}
	}

	private void SendStatisticsOnStartRound()
	{
		Dictionary<string, string> dictionary = new Dictionary<string, string>();
		if (PhotonNetwork.room != null)
		{
			string text = (string)PhotonNetwork.room.customProperties["pass"];
			string text2 = ((text == null || !string.IsNullOrEmpty(text.ToString())) ? "private" : string.Empty);
			string text3 = string.Empty;
			switch (GameController.instance.curTypeGame)
			{
			case TypeGame.tanks:
				text3 = "Tanks ";
				break;
			case TypeGame.Zombe:
				text3 = "Zombe";
				break;
			case TypeGame.TDM:
				text3 = "Team Deathmatch ";
				break;
			case TypeGame.CopsAndRobbers:
				text3 = "Cops And Robbers";
				break;
			case TypeGame.RocketLeague:
				text3 = "Rocket League";
				break;
			case TypeGame.SkyBlock:
				text3 = "SkyBlock";
				break;
			case TypeGame.Pixelmon:
				text3 = "Pixelmon";
				break;
			case TypeGame.WalkingRobots:
				text3 = "Walking Robots";
				break;
			case TypeGame.TitanfallV2:
				text3 = "Titanfall V2";
				break;
			}
			dictionary.Add("Tier " + CupsManager.CurrentTier, text3 + text2);
			FlurryWrapper.LogEvent(FlurryWrapper.EV_MULTIPLAYER_MODE_RATING, dictionary);
			dictionary.Clear();
			dictionary.Add("Round", text3);
			FlurryWrapper.LogEvent(FlurryWrapper.EV_ROUNDS_COUNT_BY_MODES, dictionary);
		}
	}

	private void OnDestroy()
	{
		myTeam = PunTeams.Team.none;
		if (_corotuneSortTeam != null)
		{
			StopCoroutine(_corotuneSortTeam);
			_corotuneSortTeam = null;
		}
		instance = null;
	}

	public void WatchPlayer(PlayerBehavior player)
	{
		_oldTeam = myTeam;
		player.AddEventListener(this, "OnPlayerDeath", delegate(UnityEngine.Object sender, object[] args)
		{
			if (GameController.instance.curTypeGame == TypeGame.Zombe)
			{
				int num = (int)args[0];
				BCWDebug.LogError(myTeam.ToString());
				_oldTeam = myTeam;
				if (myTeam == PunTeams.Team.blue)
				{
					ZombieModePlayerStatistics.team = PunTeams.Team.red;
					ZombieModePlayerStatistics.wasInfected = true;
					ZombieModePlayerStatistics.surviveTimeInSeconds = (float)PVPManager.instance.GetTime() - Mathf.Abs((float)((double)ZombieModePlayerStatistics.enterGameModeTime - Convert.ToDouble(PhotonNetwork.room.customProperties["StartRoundTime"])));
					bool flag = false;
					if (1 < args.Length)
					{
						flag = (bool)args[1];
					}
					if (!flag)
					{
						UpdateTeamPlayer((PlayerBehavior)sender, PunTeams.Team.red);
						SendMasterMyTeam(((PlayerBehavior)sender).photonView.ownerId, PunTeams.Team.red);
					}
					if (TDMController.ChangeTeam != null)
					{
						TDMController.ChangeTeam();
					}
				}
			}
		});
		player.AddEventListener(this, "OnPlayerRespawn", delegate(UnityEngine.Object sender, object[] args)
		{
			if (GameController.instance.curTypeGame == TypeGame.Zombe)
			{
				MarketController.Instance.SetWeaponSetForZombe(((PlayerBehavior)sender).localTeam, cGraid, myTeam != _oldTeam);
			}
		});
	}

	public void WaitTeamAndSpawnPointOnRestart(Action callback)
	{
		if (WaitForTeamCoroutine != null)
		{
			CoroutineRunner.Instance.StopCoroutine(WaitForTeamCoroutine);
		}
		WaitForTeamCoroutine = CoroutineRunner.Instance.StartCoroutine(WaitForTeam(callback));
	}

	private IEnumerator WaitForTeam(Action callback)
	{
		float start = Time.realtimeSinceStartup;
		while (PlayerBehavior.MyPlayer.localTeam == PunTeams.Team.none && Time.realtimeSinceStartup < start + 5f)
		{
			yield return null;
		}
		callback();
		float timeForRespawn = 2f;
		if (PlayerBehavior.MyPlayer != null)
		{
			PlayerBehavior.MyPlayer.FirstSpawn(timeForRespawn);
		}
	}

	public void SetPlayerPoint(PhotonPlayer player, int value)
	{
		player.SetScore(value);
	}

	public void AddTeamPoints(PunTeams.Team team, int value)
	{
		if (GameController.instance.IsFlagGameType())
		{
			switch (team)
			{
			case PunTeams.Team.blue:
				if (BCWFlagController.instance != null)
				{
					BCWFlagController.instance.countBlueTeam += value;
				}
				break;
			case PunTeams.Team.red:
				if (BCWFlagController.instance != null)
				{
					BCWFlagController.instance.countRedTeam += value;
				}
				break;
			}
		}
		else if (PhotonNetwork.room.customProperties.ContainsKey(team.ToString()))
		{
			PhotonNetwork.room.SetCustomProperties(new ExitGames.Client.Photon.Hashtable { 
			{
				team.ToString(),
				(int)PhotonNetwork.room.customProperties[team.ToString()] + value
			} });
		}
	}

	public void ResetTeam()
	{
		bool flag = false;
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			BCWDebug.LogError(string.Format("Send player {0} {1} team", listPlayer.nick.ToString(), (!flag) ? "blue" : "red"), "TDM");
			if (flag)
			{
				PVPManager.instance.photonView.RPC("SetTeam", PhotonPlayer.Find(listPlayer.ownerId), PunTeams.Team.red, false);
			}
			else
			{
				PVPManager.instance.photonView.RPC("SetTeam", PhotonPlayer.Find(listPlayer.ownerId), PunTeams.Team.blue, false);
			}
			flag = !flag;
		}
	}

	public static TDMResult MyTeamResult()
	{
		TDMResult flagResult = GetFlagResult();
		if (flagResult != TDMResult.None)
		{
			return flagResult;
		}
		return GameController.instance.CurrentGameMode.GetRoundResult();
	}

	private static TDMResult GetFlagResult()
	{
		if (BCWFlagManager.instance != null && BCWFlagManager.instance.winerTeam != 0)
		{
			return (BCWFlagManager.instance.winerTeam != myTeam) ? TDMResult.Loser : TDMResult.Winner;
		}
		if (BCWFlagController.instance != null && BCWFlagController.instance.winnerTeam != TDMResult.None)
		{
			return BCWFlagController.instance.winnerTeam;
		}
		if (BCWFlagController.instance != null && GameController.instance.IsFlagGameType())
		{
			if (BCWFlagController.instance.countBlueTeam > BCWFlagController.instance.countRedTeam)
			{
				return (myTeam != PunTeams.Team.blue) ? TDMResult.Loser : TDMResult.Winner;
			}
			if (BCWFlagController.instance.countBlueTeam < BCWFlagController.instance.countRedTeam)
			{
				return (myTeam == PunTeams.Team.blue) ? TDMResult.Loser : TDMResult.Winner;
			}
			return TDMResult.Draw;
		}
		return TDMResult.None;
	}

	public void GetBonuse()
	{
		nGradeWeapon -= cGraid;
		for (int i = 0; i < nGradeWeapon; i++)
		{
			cGraid++;
			MarketController.Instance.SetWeaponSetForZombe(PunTeams.Team.blue, cGraid);
		}
		DestroyUpBonuse();
	}

	public void DestroyUpBonuse()
	{
		foreach (GameObject item in listUpBonuse)
		{
			UnityEngine.Object.Destroy(item);
		}
		listUpBonuse.Clear();
	}

	public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
	{
		if (!isTeamGameType)
		{
			return;
		}
		if (stream.isWriting)
		{
			stream.SendNext(incrementTeams);
			stream.SendNext(_localTeam.Count);
			{
				foreach (LocalTeam item2 in _localTeam)
				{
					stream.SendNext(item2.idPlayer);
					stream.SendNext(item2.team);
				}
				return;
			}
		}
		int num = (int)stream.ReceiveNext();
		if (num != incrementTeams)
		{
			ClearTeams();
		}
		incrementTeams = num;
		int num2 = (int)stream.ReceiveNext();
		List<LocalTeam> list = new List<LocalTeam>();
		for (int i = 0; i < num2; i++)
		{
			LocalTeam item = default(LocalTeam);
			item.idPlayer = (int)stream.ReceiveNext();
			item.team = (PunTeams.Team)(byte)stream.ReceiveNext();
			if (_localTeam.Select((LocalTeam x) => x.idPlayer).ToList().Contains(item.idPlayer))
			{
				foreach (LocalTeam item3 in _localTeam)
				{
					if (item3.idPlayer == item.idPlayer)
					{
						if (item3.team == PunTeams.Team.none && item.team != 0 && !UpdateTeamPlayer(item3.idPlayer, item.team))
						{
							item.team = PunTeams.Team.none;
						}
						if (GameController.instance.curTypeGame == TypeGame.Zombe && item3.team != item.team)
						{
							UpdateTeamPlayer(item3.idPlayer, item.team);
						}
					}
				}
			}
			else if (!UpdateTeamPlayer(item.idPlayer, item.team))
			{
				item.team = PunTeams.Team.none;
			}
			list.Add(item);
		}
		_localTeam.Clear();
		_localTeam = list;
	}

	public void ChangeTeamFromMaster(int ownerId, PunTeams.Team punTeam)
	{
		if (!PhotonNetwork.isMasterClient)
		{
			return;
		}
		bool flag = false;
		for (int i = 0; i < _localTeam.Count; i++)
		{
			if (ownerId != _localTeam[i].idPlayer)
			{
				continue;
			}
			flag = true;
			LocalTeam value = _localTeam[i];
			if (GameController.instance != null && GameController.instance.curTypeGame == TypeGame.Zombe)
			{
				if (!UpdateTeamPlayer(ownerId, punTeam))
				{
					BCWDebug.LogError("not found player");
					punTeam = PunTeams.Team.none;
				}
				value.team = punTeam;
				_localTeam[i] = value;
			}
			else
			{
				if (value.team == PunTeams.Team.none && !UpdateTeamPlayer(ownerId, punTeam))
				{
					BCWDebug.LogError("not found player");
					punTeam = PunTeams.Team.none;
				}
				value.team = punTeam;
				_localTeam[i] = value;
			}
		}
		if (!flag)
		{
			_localTeam.Add(new LocalTeam
			{
				idPlayer = ownerId,
				team = punTeam
			});
			StartCoroutine(WaitPlayer(ownerId, punTeam));
		}
	}

	private IEnumerator WaitPlayer(int ownerID, PunTeams.Team team)
	{
		float timeForExit = 10f;
		while (true)
		{
			foreach (LocalTeam item in _localTeam)
			{
				if (item.idPlayer == ownerID)
				{
					ChangeTeamFromMaster(ownerID, team);
					yield break;
				}
			}
			if (timeForExit <= 0f)
			{
				break;
			}
			yield return new WaitForSeconds(1f);
			timeForExit -= 1f;
		}
	}

	public void ChangePlayerTeam()
	{
		for (int i = 0; i < _localTeam.Count; i++)
		{
			LocalTeam value = _localTeam[i];
			if (value.idPlayer == GameController.instance.listPlayers[1].ownerId)
			{
				value.team = ((GameController.instance.listPlayers[1].localTeam == PunTeams.Team.blue) ? PunTeams.Team.red : PunTeams.Team.blue);
				BCWDebug.LogError(GameController.instance.listPlayers[1].nick + "  enemy team " + value.team);
				_localTeam[i] = value;
			}
		}
	}

	private IEnumerator CorotuneSortTeam()
	{
		if (isTeamGameType)
		{
			while (true)
			{
				SortTeam();
				yield return new WaitForSeconds(0.5f);
			}
		}
	}

	private void SortTeam()
	{
		if (IOSInternetConnection.isEnable && PlayerBehavior.MyPlayer != null && (PlayerBehavior.MyPlayer.localTeam == PunTeams.Team.none || myTeam == PunTeams.Team.none))
		{
			UpdateTeamPlayer(PlayerBehavior.MyPlayer, PunTeams.Team.red);
			myTeam = PunTeams.Team.blue;
		}
		else
		{
			if (!PhotonNetwork.isMasterClient)
			{
				return;
			}
			List<LocalTeam> list = new List<LocalTeam>();
			TypeGame curTypeGame = GameController.instance.curTypeGame;
			if (curTypeGame == TypeGame.Zombe)
			{
				foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
				{
					LocalTeam item = default(LocalTeam);
					item.idPlayer = listPlayer.ownerId;
					if (listPlayer.localTeam == PunTeams.Team.none)
					{
						if (PlayerBehavior.MyPlayer == listPlayer && zombieStart == 0)
						{
							item.team = PunTeams.Team.red;
						}
						else
						{
							item.team = PunTeams.Team.blue;
						}
						UpdateTeamPlayer(listPlayer, item.team);
					}
					else
					{
						foreach (LocalTeam item3 in _localTeam)
						{
							if (item.idPlayer == item3.idPlayer)
							{
								item.team = item3.team;
								if (listPlayer.localTeam != item3.team)
								{
									UpdateTeamPlayer(listPlayer, item.team);
								}
							}
						}
					}
					list.Add(item);
				}
				_localTeam.Clear();
				_localTeam = list;
				return;
			}
			int num = 0;
			int num2 = 0;
			foreach (LocalTeam item4 in _localTeam)
			{
				if (item4.team == PunTeams.Team.blue)
				{
					num2++;
				}
				if (item4.team == PunTeams.Team.red)
				{
					num++;
				}
			}
			foreach (PlayerBehavior listPlayer2 in GameController.instance.listPlayers)
			{
				LocalTeam item2 = default(LocalTeam);
				item2.idPlayer = listPlayer2.ownerId;
				if (listPlayer2.localTeam == PunTeams.Team.none)
				{
					if (num2 > num)
					{
						item2.team = PunTeams.Team.red;
						num++;
					}
					else
					{
						item2.team = PunTeams.Team.blue;
						num2++;
					}
					UpdateTeamPlayer(listPlayer2, item2.team);
				}
				else
				{
					foreach (LocalTeam item5 in _localTeam)
					{
						if (item2.idPlayer == item5.idPlayer)
						{
							item2.team = item5.team;
						}
					}
				}
				list.Add(item2);
			}
			_localTeam.Clear();
			_localTeam = list;
		}
	}

	public void ClearTeams()
	{
		if (!isTeamGameType)
		{
			return;
		}
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			listPlayer.localTeam = PunTeams.Team.none;
		}
		_localTeam.Clear();
	}

	private bool UpdateTeamPlayer(PlayerBehavior player, PunTeams.Team team)
	{
		if (isTeamGameType)
		{
			if (GameController.instance != null && GameController.instance.curTypeGame == TypeGame.Zombe && player == PlayerBehavior.MyPlayer && player.localTeam == PunTeams.Team.red)
			{
				return true;
			}
			player.localTeam = team;
			if (player == PlayerBehavior.MyPlayer)
			{
				myTeam = team;
				if (GameInfoWindow.instance != null)
				{
					GameInfoWindow.instance.ChangeColorTeam();
				}
				if (TDMColorScroll.instance != null)
				{
					TDMColorScroll.instance.ChangeColorTeam();
				}
			}
			player.OnTeamChanged();
			UpdateCountTeam();
			if (!PVPManager.instance.endOfRound)
			{
				GameInfoWindow.instance.UpdateScrollForCurrentGameMode();
			}
		}
		return true;
	}

	private bool UpdateTeamPlayer(int idPlayer, PunTeams.Team team)
	{
		if (isTeamGameType)
		{
			foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
			{
				if (idPlayer == listPlayer.ownerId)
				{
					UpdateTeamPlayer(listPlayer, team);
					return true;
				}
			}
		}
		return false;
	}

	public void CheckPlayerTeam(PlayerBehavior player)
	{
		if (!isTeamGameType)
		{
			return;
		}
		foreach (LocalTeam item in _localTeam)
		{
			if (item.idPlayer == player.ownerId && item.team != player.localTeam)
			{
				UpdateTeamPlayer(player, item.team);
				break;
			}
		}
	}

	public PunTeams.Team FindTeamPlayer(int ownerId)
	{
		if (isTeamGameType)
		{
			foreach (LocalTeam item in _localTeam)
			{
				if (item.idPlayer == ownerId)
				{
					return item.team;
				}
			}
		}
		return PunTeams.Team.none;
	}

	public void UpdateCountTeam()
	{
		int num = 0;
		int num2 = 0;
		foreach (PlayerBehavior listPlayer in GameController.instance.listPlayers)
		{
			if (listPlayer.localTeam == PunTeams.Team.red)
			{
				num++;
			}
			else if (listPlayer.localTeam == PunTeams.Team.blue)
			{
				num2++;
			}
		}
		BCWDebug.LogError("Count Red team " + num + " Count Blue teram  " + num2);
		_countRedTeam = num;
		_countBlueTeam = num2;
	}

	public int CountTeam(PunTeams.Team team)
	{
		switch (team)
		{
		case PunTeams.Team.blue:
			return _countBlueTeam;
		case PunTeams.Team.red:
			return _countRedTeam;
		default:
			return _localTeam.Count;
		}
	}

	[PunRPC]
	public void SendMasterMyTeam(int ownerId, PunTeams.Team team)
	{
		if (PhotonNetwork.isMasterClient)
		{
			BCWDebug.LogError("master");
			ChangeTeamFromMaster(ownerId, team);
			return;
		}
		CoroutineRunner.Invoke(0.5f, delegate
		{
			PVPManager.instance.photonView.RPC("SendMasterMyTeam", PhotonTargets.MasterClient, ownerId, team);
		});
	}

	public IEnumerator WaitRestartTDM()
	{
		while (!ManagerPreloadingSectors.thisScript.sectorsLoaded || PlayerBehavior.MyPlayer.localTeam == PunTeams.Team.none || PVPManager.instance.gameEnded)
		{
			BCWDebug.LogError(string.Concat("Wait Restart...  sectorsLoaded = ", ManagerPreloadingSectors.thisScript.sectorsLoaded, "   PhotonNetwork.player.GetTeam( = ", PlayerBehavior.MyPlayer.localTeam, "  PVPManager.instance.gameEnded = ", PVPManager.instance.gameEnded));
			yield return null;
			if (ManagerPreloadingSectors.thisScript.sectorsLoaded && IOSInternetConnection.isEnable)
			{
				break;
			}
		}
		SpawnPointChief.SpawnPoint spawnPoint = SpawnPointChief.instance.getRandomPointForTDM(PlayerBehavior.MyPlayer);
		StartCoroutine(ManagerPreloadingSectors.thisScript.LoadSectorsNearPoint(new Vector2(spawnPoint.position.x, spawnPoint.position.z)));
		while (!ManagerPreloadingSectors.thisScript.sectorsLoaded)
		{
			yield return new WaitForSeconds(0.3f);
		}
		instance.SetStartPVP(true);
		GameController.instance.RestartLevel(spawnPoint);
		while (PlayerBehavior.MyPlayer == null || PlayerBehavior.MyPlayer.tController == null || !PlayerBehavior.MyPlayer.tController.enabled)
		{
			yield return null;
		}
		yield return null;
		float delay = ((GameController.instance.curTypeGame != TypeGame.SkyBlock) ? 0f : 2.5f);
		CoroutineRunner.Invoke(delay, delegate
		{
			if (PlayerBehavior.MyPlayer.tController.enabled)
			{
				Debug.LogError("HideInterface");
				GameInfoWindow.instance.HideInterface();
				MapWindow.instance.gameObject.SetActive(true);
			}
		});
	}
}
